package com.lenovo.uitest.base;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.R.integer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.ParseException;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.AndroidException;

import com.android.uiautomator.core.UiCollection;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.core.UiWatcher;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;

public class LenovoUiTestCase extends UiAutomatorTestCase {


	
	// 对象·条件·动作 uiautomator类封装	
	public static UiDevice device() {
		return UiDevice.getInstance();
	}
	public UiObject object(UiSelector selector) {
		return new UiObject(selector);
	}
	public UiSelector selector() {
		return new UiSelector();
	}
	public UiScrollable scrollable(UiSelector selector) {
		return new UiScrollable(selector());
	}
	public UiCollection collection(UiSelector selector) {
		return new UiCollection(selector());
	}
/**
 * 需求：发送信息到报告中，参数为code识别码，和一个键值对
 * @param code
 * @param key
 * @param value
 */
	public void sendReportStatus(int code,String key,String value) {
		Bundle bundle=new Bundle();
		bundle.putString(key, value);
		getAutomationSupport().sendStatus(code, bundle);		
	}
	/**
	 * 需求：截图
	 * 
	 * @param className
	 * @throws UiObjectNotFoundException
	 * @throws AndroidException
	 */
	public void screenShot(String path, String fileName, int i) {
		UiDevice device = UiDevice.getInstance();
		String language;
		language = getLanguage();
		File f = new File(path + "/" + language);
		if (!f.exists()) {
			f.mkdirs();
		}
		SimpleDateFormat formattime = new SimpleDateFormat("yyyyMMddHHmm");
		long time = System.currentTimeMillis();
		String nowTime = formattime.format(new Date(time));
		String Name = language + "_" + nowTime + "_" + fileName + i + ".png";
		sleep(2000);
		device.takeScreenshot(new File(f + Name));
	}

	/**
	 * 需求：解锁
	 * 
	 * @param className
	 * @return
	 * @throws UiObjectNotFoundException
	 * @throws RemoteException
	 * @throws AndroidException
	 */
	public boolean Unlock(){
		if (!isLock()) {
			return true;
		}
		int i = 0, j = 0;
        
		try {
			do {				
					UiDevice.getInstance().wakeUp();
				
			} while (!device().isScreenOn() && i++ < 10);
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		int width = device().getDisplayWidth();
		int height = device().getDisplayHeight();

		sleep(800);
		// 默认解锁
		device().swipe(width / 2, height - 10, width / 2, 100, 10);
		if (!isLock()) {
			return true;
		}
		do {
			//圈圈解锁
			device().swipe(width / 2, height - height / 5, width, height - height/ 5, 10);
			if (!isLock()) {
				return true;
			}
			//主题解锁
			device().swipe(width / 2, height * 68 / 100, width,height * 68 / 100, 10);
			if (!isLock()) {
				return true;
			}
			//平板解锁
			device().swipe(4 * width / 5, height / 2, 4 * width / 5, height - 10,10);
			if (!isLock()) {
				return true;
			}
		} while (isLock() && j++ < 5);
		return false;
	}

	/**
	 * 需求：判断是否是锁屏
	 * 
	 * @return
	 */
	public boolean isLock() {
		String lockPackage = "android|com.lenovo.lockscreen.*|com.android.keyguard";
		return device().getCurrentPackageName().matches(lockPackage);
	}

	/**
	 * 需求：启动应用
	 * 
	 * @param component
	 * @param action
	 * @throws IOException
	 */
	public boolean LaunchApp(String packageName, String activity) {
		String cmd = "am start -W -n " + packageName + "/" + activity;
		int i = 0;
		while (!packageName.equals(device().getCurrentPackageName())) {
			try {
				Process process=Runtime.getRuntime().exec(cmd);
				process.waitFor();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			sleep(800);
			if (i++ > 5) {
				return false;
			}
		}
		return packageName.equals(device().getCurrentPackageName());
	}
	/**
	 * 需求：通过action来拨号
	 * @param phone
	 */
	public void callPhoneForAmAction(String phone) {
		String cmd="am start -a android.intent.action.CALL -d tel:"+phone;
		Process process;
		try {
			process = Runtime.getRuntime().exec(cmd);
			process.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}

	/**
	 * 需求：关闭所有应用
	 */
	public void closeAllApp() {

		
		
		try {
			UiDevice.getInstance().wakeUp();
			sleep(1000);
			UiDevice.getInstance().pressRecentApps();
			
			//k7清除后台
			if (Build.VERSION.RELEASE.matches(".*4\\.4.*")) {
				sleep(1000);
				
				//UiObject clear=object(selector().className("android.widget.ImageView").index(1));
				//UiObject sys=object(selector().resourceId("com.android.systemui:id/clear_anim_image"));
				UiObject clear=object(selector().resourceId("com.android.systemui:id/cover_image"));
				UiObject recent = object(selector().textMatches("最近|Recent"));
				
				if (clear.exists()) {
					try {
						sleep(500);
						recent.swipeRight(50);
						sleep(500);
						recent.click();
						sleep(500);
						clear.click();
						sleep(500);
						device().pressHome();
						return;
					} catch (UiObjectNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
			
			
			
			//其他清除后台
			
			sleep(1000);
			UiObject CloseAllApp = new UiObject(new UiSelector().className(
					"android.widget.Button").instance(0));

			if (CloseAllApp.exists()) {
				CloseAllApp.click();
			} else {
				UiObject obj = new UiObject(
						new UiSelector().className("android.widget.ScrollView"));
				while (obj.exists()) {
					obj.swipeRight(5);
				}

			}
			sleep(2000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 需求： 查找文本
	 * 
	 * @param text
	 * @param instance
	 * @return
	 * @throws UiObjectNotFoundException
	 */
	public Boolean isText(String text, int instance)
			throws UiObjectNotFoundException {
		String regex = ".*" + text + ".*";
		UiCollection textCollection = new UiCollection(
				new UiSelector().index(0));
		UiObject obj = textCollection.getChildByInstance(
				new UiSelector().textMatches(regex), instance);
		if (obj.exists()) {
			return true;
		} else {
			return false;
		}
	}

	public Boolean isText(String Text) {
		String regex = ".*" + Text + ".*";
		return object(selector().textMatches(regex)).exists();
	}

	/**
	 * 需求：获取指定坐标的颜色值
	 * 
	 * @param x
	 * @param y
	 * @return
	 * @throws UiObjectNotFoundException
	 */
	public int getColorFofPixel(int x, int y) throws UiObjectNotFoundException {
		UiDevice.getInstance().takeScreenshot(new File("/sdcard/dsc1.png"));
		Bitmap m = BitmapFactory.decodeFile("/sdcard/dsc1.png");
		int color = m.getPixel(x, y);
		return color;
	}

	/**
	 * 需求： 需求：通过KEYCODE直接输入，想要的字符串，不需要获取编辑框对象
	 * 
	 * @param input
	 * @throws UiObjectNotFoundException
	 */
	public void inputStrintByKeycode(String input)
			throws UiObjectNotFoundException {
		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c >= 48 && c <= 57) {
				UiDevice.getInstance().pressKeyCode(c - 41);
			} else if (c >= 97 && c <= 122) {
				UiDevice.getInstance().pressKeyCode(c - 68);
			} else if (c >= 65 && c <= 90) {
				UiDevice.getInstance().pressKeyCode(59);
				sleep(20);
				UiDevice.getInstance().pressKeyCode(c - 36);
			} else if (c == 32) {
				UiDevice.getInstance().pressKeyCode(62);
			} else {
				System.out
						.println("Please modify the method supports the characters that you enter");
			}
		}
	}

	/**
	 * 需求：需求：获取当前系统的时间，到毫秒
	 * 
	 * @return
	 */
	public String getCurrentSysTime() {
		SimpleDateFormat formattime1 = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss:SSS");
		long ctime = System.currentTimeMillis();
		String currenttime = formattime1.format(new Date(ctime));
		System.out.println(currenttime);
		return currenttime;
	}

	/**
	 * 需求： 计算两个时间差，精度到毫秒（ 范翰卿 ）
	 * 
	 * @param time1
	 * @param time2
	 * @return
	 * @throws ParseException
	 * @throws java.text.ParseException
	 */
	public long getTimeDistance(String time1, String time2)
			throws ParseException, java.text.ParseException {
		SimpleDateFormat formattime1 = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss:SSS");
		Date t1 = formattime1.parse(time1);
		Date t2 = formattime1.parse(time2);
		long d = t1.getTime() - t2.getTime();
		System.out.println(d);
		return d;

	}

	/**
	 * 需求：获取系统语言，并返回系统语言值
	 * 
	 * @return
	 */
	public String getLanguage() {
		Locale locale = Locale.getDefault();
		String Language = locale.getLanguage();
		return Language;
	}

	/**
	 * 需求：对比两个下标数量相同的字符串数组是否相等
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public boolean isStringEquals(String[] a, String[] b) {
		boolean compare = true;
		for (int i = 0; i < a.length; i++) {
			if (!(a[i].equals(b[i]))) {
				compare = false;
			}
		}
		return compare;
	}

	/**
	 * 需求：获取界面元素类的个数与5个textview的字符串，返回一个字符串数组，用于判断界面是否变化
	 * 
	 * @return
	 * @throws UiObjectNotFoundException
	 */
	public String[] isUiChange() throws UiObjectNotFoundException {
		UiCollection framCollection = new UiCollection(
				new UiSelector().className("android.widget.FrameLayout"));
		int count = 0;
		String[] ts = { "a", "a", "a", "a", "a" };
		if (framCollection.exists()) {
			int textcount = framCollection.getChildCount(new UiSelector()
					.className("android.widget.TextView"));
			int linearcount = framCollection.getChildCount(new UiSelector()
					.className("android.widget.LinearLayout"));
			int viewcount = framCollection.getChildCount(new UiSelector()
					.className("android.view.View"));
			count = textcount + linearcount + viewcount;
		}
		for (int j = 0; j < 5; j++) {
			UiObject textObject = new UiObject(new UiSelector().className(
					"android.widget.TextView").instance(j));
			if (textObject.exists()) {
				ts[j] = textObject.getText();
			} else {
				break;
			}
		}
		String[] change = { String.valueOf(count), ts[0], ts[1], ts[2], ts[3],
				ts[4] };
		return change;
	}

	/**
	 * 需求： 滑动列表到某个文本并且点击它
	 * 
	 * @param text
	 * @throws UiObjectNotFoundException
	 */
	public void clickListTextByscrollToView(String text)
			throws UiObjectNotFoundException {
		int x = UiDevice.getInstance().getDisplayWidth();
		int y = UiDevice.getInstance().getDisplayHeight();
		boolean b = true;
		UiObject textObject = new UiObject(new UiSelector().text(text));
		int i = 0;
		do {
			UiDevice.getInstance().swipe(x / 2, y - 200, x / 2, y - 600, 10);
			if (textObject.exists()) {
				b = false;
				textObject.clickAndWaitForNewWindow();
			}
		} while (b && ++i < 30);

	}

	/**
	 * 需求：监听器
	 */
	public void Moniter() {
		final UiDevice device = UiDevice.getInstance();
		final UiObject objKnow = new UiObject(
				new UiSelector().textContains("知道了"));
		final UiObject objMessage = new UiObject(
				new UiSelector().textContains("已读"));

		device.registerWatcher("moniter", new UiWatcher() {
			public boolean checkForCondition() {
				if (objKnow.exists()) {
					device.pressBack();
					return true;
				}

				if (objMessage.exists()) {
					sleep(2000);
					device.pressBack();
					return true;
				}

				return false;
			}
		});
	}

}
